#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mg_Sys_Led.h"
#include "mg_HTR3212.h"

//毫秒级延时（非阻塞）
void HTR3212_Delay_Ms(uint32_t ms)
{
	usleep(1000 * ms);
}
//LED芯片GPIO初始化
void HTR3212_GPIO_Init(void)
{
	ithGpioSetMode(HTR3212_RST_Pin, ITH_GPIO_MODE0);
	ithGpioSetOut(HTR3212_RST_Pin);
	ithGpioClear(HTR3212_RST_Pin);
	usleep(10);
	ithGpioSet(HTR3212_RST_Pin);
}
//写寄存器
uint32_t HTR3212WriteReg(uint8_t REG_Address, uint8_t Data)
{
	return I2C0_Write_8Reg(HTR3212_LED_DEVICE_ADDR, REG_Address, &Data, 1);
}
//写多个寄存器
void HTR3212WriteMultiReg(uint8_t Start_REG_Address, uint8_t *dat, uint8_t data_len)
{
	I2C0_Write_8Reg(HTR3212_LED_DEVICE_ADDR, Start_REG_Address, dat, data_len);
}
//EEPROM读一个字节
uint8_t HTR3212ReadReg(uint8_t Start_REG_Address)
{
	return (I2C0_Read_8Reg(HTR3212_LED_DEVICE_ADDR, Start_REG_Address));
}
//控制单个Led
void HTR3212_Set_SingleLed(uint8_t Led_Num, uint8_t PWM)
{
	HTR3212WriteReg(HTR3212_LEDPWM0 + Led_Num, PWM);
	HTR3212WriteReg(HTR3212_PWM_UPDATA, 0);
}
//所有SinglePwm设置
void HTR3212SetAllPWMSame(uint8_t duty)
{
	uint8_t AllDuty[12];
	memset(AllDuty, duty, sizeof(AllDuty));
	HTR3212WriteMultiReg(HTR3212_LEDPWM0, AllDuty, sizeof(AllDuty));
	HTR3212WriteReg(HTR3212_PWM_UPDATA, 0);
}
//所有SinglePwm设置(不同值)
void HTR3212SetAllPWM(uint8_t* duty)
{
	HTR3212WriteMultiReg(HTR3212_LEDPWM0, duty, 12);
	HTR3212WriteReg(HTR3212_PWM_UPDATA, 0);
}
//RGB测试
void HTR3212_TEST(void)
{
	uint8_t i = 0;
	for (i = 0; i<12; i++)
	{
		HTR3212_Set_SingleLed(i, 0xFF);
		HTR3212_Delay_Ms(40);
	}
	for (i = 0; i<12; i++)
	{
		HTR3212_Set_SingleLed(i, 0);
		HTR3212_Delay_Ms(40);
	}
}
//RGB驱动初始化
uint32_t HTR3212_Init(void)
{
	uint32_t ret, i;
	printf("Moorgen INFO:Try to init HTR3212.\n");
	HTR3212_GPIO_Init();
	ret = HTR3212WriteReg(HTR3212_SHUTDOWN, 0x1);
	for (i = 0; i < LED_NUM; i++)
		HTR3212WriteReg(HTR3212_LED0_SWITCH + i, 1);
	HTR3212WriteReg(HTR3212_LED_FREQUENCY, 1);
	HTR3212WriteReg(HTR3212_ALL_SWITCH, 0);
	HTR3212SetAllPWMSame(0);
	HTR3212_TEST();
	return ret;
}